package org.feng.navigation.domain.rpc.youdao.domainservice;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.feng.navigation.domain.rpc.youdao.domainobject.YouDaoTextTranslationRequest;
import org.feng.navigation.domain.rpc.youdao.domainobject.YouDaoTextTranslationResponse;
import org.feng.navigation.domain.rpc.youdao.gateway.YouDaoHttpClient;
import org.feng.navigation.domain.youdao.entity.TextTranslateObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 有道API接口服务实现
 *
 * @version V1.0
 * @author: junzi
 * @date: 2023年01月18日 14时40分
 */
@Slf4j
@Service
public class YouDaoApiServiceImpl implements YouDaoApiService {

    @Resource
    private YouDaoHttpClient youDaoHttpClient;

    @Override
    public void textTranslate(TextTranslateObject textTranslateObject) {
        YouDaoTextTranslationRequest request = new YouDaoTextTranslationRequest();
        request.setFrom(textTranslateObject.getFrom().getCode());
        request.setQ(textTranslateObject.getItemText());
        request.setTo(textTranslateObject.getTo().getCode());

        YouDaoTextTranslationResponse response = youDaoHttpClient.executeTextTranslate(request);
        if (!response.isSuccess()) {
            textTranslateObject.setErrorMessage(response.getErrorMessage());
            return;
        }
        List<String> translationList = response.getTranslationList();
        if (CollectionUtil.isEmpty(translationList)) {
            textTranslateObject.setErrorMessage("翻译错误，没有结果");
            return;
        }
        textTranslateObject.setTranslation(translationList.get(0));
    }
}
